package com.gitee.wsl.doc.prosemirror.state.command.mark

import com.gitee.wsl.doc.prosemirror.model.mark.MarkType
import com.gitee.wsl.doc.prosemirror.model.node.ext.getMarkLocation
import com.gitee.wsl.doc.prosemirror.state.Command
import com.gitee.wsl.doc.prosemirror.state.CommandDispatch
import com.gitee.wsl.doc.prosemirror.state.EditorState
import com.gitee.wsl.doc.prosemirror.transform.ext.removeMark

class RemoveMark(val markType: MarkType): Command {
    override fun exec(
        state: EditorState,
        dispatch: CommandDispatch?,
    ): Boolean {
        val markLocation =
            if (!state.selection.isEmpty)
                state.selection.posRange
            else
                state.tr.doc.getMarkLocation( state.selection._anchor.pos, markType)

        if (markLocation == null) {
            return false
        }

        dispatch?.apply(state.tr.removeMark(markLocation.first, markLocation.second, markType))
        return true
    }
}

fun Command.Companion.removeMark( markType: MarkType) = RemoveMark(markType)